<script setup lang="ts">
import { addRoleAPI, editRoleAPI, getRoleDetailAPI, getTreeListAPI } from '@/apis/system';
import type { AddRoleParams, TreeList } from '@/types/system';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import type { TreeInstance } from 'element-plus/lib/components/index.js';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';


// 创建添加角色所需表单
const form = ref<AddRoleParams>({
  roleName: '',
  remark: '',
  perms: []
})
// 表单校验规则
const rules = ref<FormRules>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
})
// 表单实例
const formRef = ref<FormInstance>()
// 获取权限树形列表
const treeList = ref<TreeList[]>()
const treeRefs = ref<TreeInstance[]>([])
const getTreeList = async () => {
  const res = await getTreeListAPI()
  treeList.value = res.data
}
getTreeList()

// 当前激活的步骤
const activeStep = ref(1)
// 上一步
const onPrev = () => {
  if (activeStep.value > 1) {
    activeStep.value--
  }
}
// 下一步
const onNext = async () => {
  try {
    if (activeStep.value === 1) {
      await formRef.value?.validate()
      activeStep.value++
    } else if (activeStep.value === 2) {
      // 遍历tree组件,获取所有选中的节点
      form.value.perms = [] // 重置form.perms
      treeRefs.value.forEach(item => {
        const checkedKeys = item.getCheckedKeys() as number[]
        // 将每个tree组件的选中节点,push到form.perms中
        form.value.perms.push(checkedKeys)
      })
      // 判断form.perms是否为空,为空则提示错误
      // 使用flat方法将二维数组转换为一维数组
      if (form.value.perms.flat().length === 0) {
        ElMessage.error('请选择权限')
      } else {
        diabledTreeRefs.value.forEach((item, index) => {
          item.setCheckedKeys(form.value.perms[index])
        })
        activeStep.value++
      }
    }
  } catch (error) {
    console.log(error);
  }
}

// 第三步表单重现
const diabledTreeRefs = ref<TreeInstance[]>([])
// 提交表单
const router = useRouter()
const onSubmit = async () => {
  // 确认框
  ElMessageBox.confirm(`确认${route.params.roleId ? '修改' : '添加'}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 提交表单
    if (route.params.roleId) {
      // 修改角色
      await editRoleAPI({...form.value, roleId: +route.params.roleId})
      ElMessage.success('修改成功')
      router.push('/sys/role')
    } else {
      // 添加角色
      await addRoleAPI(form.value)
      ElMessage.success('添加成功')
      router.push('/sys/role')
    }

  }).catch(() => { })
}

// --------编辑角色----------
// 数据回显
const route = useRoute()
const getRoleDetail = async () => {
  if (route.params.roleId) {
    const res = await getRoleDetailAPI(+route.params.roleId)
    const { roleName, remark, perms } = res.data
    form.value = {
      roleName,
      remark,
      perms
    }
  }
}
getRoleDetail()
</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header content="添加角色" @back="$router.back()" />
      <div style="font-size: 14px;line-height: 18px;">{{ form }}</div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
        {{ activeStep }}
      </div>
      <div v-show="activeStep === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form class="roleInfoForm" :model="form" :rules="rules" ref="formRef">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="form.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入角色描述" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="activeStep === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree :data="item.children" show-checkbox default-expand-all node-key="id" :props="{ label: 'title' }"
                ref="treeRefs" :default-checked-keys="form.perms[index]" />
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeStep === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ form.roleName }}</div>
            <div class="form-item">角色描述：{{ form.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree :data="item.children" show-checkbox default-expand-all node-key="id"
                  :props="{ label: 'title', disabled: () => true }" ref="diabledTreeRefs" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button :type="activeStep === 1 ? '' : 'primary'" @click="onPrev">上一步</el-button>
        <el-button v-if="activeStep < 3" type="primary" @click="onNext">下一步</el-button>
        <el-button v-if="activeStep === 3" type="primary" @click="onSubmit" style="width: 73.12px;">完成</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}

.roleInfoForm {
  display: flex;
  flex-direction: column;
  width: 350px;
}

:deep(.el-tree-node[aria-checked="true"]) {
  background-color: #f6f6f6c8;
  /* 设置复选框选中项的背景颜色 */
}
</style>